<template>
    <div>
    <h2>SSE 数据流</h2>
    <p>单条数据：{{ message }}</p>
    <!-- <p>数据列表：{{ list }}</p> -->
    <ul>
      <li v-for="(item, index) in list" :key="index">
        {{ item.responseName }} - {{ item.responseInfo }}
      </li>
    </ul>
  </div>

</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";

const message = ref("");
const list = ref([]);

let eventSource1, eventSource2;

onMounted(() => {
  // 监听单条数据流
  // eventSource1 = new EventSource("http://localhost:8086/api/sse/data");

  // eventSource1.onopen = () => {
  //   console.log("SSE 连接成功！");
  // };
  // eventSource1.onmessage = (event) => {
  //   console.log("收到数据:", event.data);
  //   message.value = event.data;
  // };
  // eventSource1.onerror = (error) => {
  //   console.error("SSE1 连接错误:", error);
  //   eventSource1.close();
  //   };
  // 监听列表数据流
  eventSource2 = new EventSource("http://localhost:8086/api/sse/list");
  eventSource2.onmessage = (event) => {
    const newData = JSON.parse(event.data);
    
    if (newData.length === 0) { 
      console.log("✅ 数据接收完毕，关闭 SSE 连接");
      eventSource2.close(); // 结束 SSE
    } else {
      list.value = [...list.value, ...newData]; // 追加数据
    }
  };

  eventSource2.onerror = (error) => {
    console.error("❌ SSE 连接错误:", error);
    eventSource2.close();
  };
  // eventSource2 = new EventSource("http://localhost:8086/api/sse/list");
  // eventSource2.onmessage = (event) => {
  //   list.value = JSON.parse(event.data);
  // };
  // eventSource1.onerror = (error) => {
  //   console.error("SSE2 连接错误:", error);
  //   eventSource2.close();
  // };
});

onUnmounted(() => {
  eventSource1?.close();
  eventSource2?.close();
});

</script>
